package com.yuanqiao.interfaceforlc.uploadmatterandfile.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.yuanqiao.interfaceforlc.uploadmatterandfile.config.config;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class margepdfUtil {
    public static Map mergepdf(List<String> fileList, String url) {
        Map map=new HashMap(2);
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //获取当前时间并作为时间戳
        String timeStamp=simpleDateFormat.format(new Date());
        String savepath = url+timeStamp+".pdf";
        File newfile=new File(savepath);
        if (!newfile.getParentFile().exists()) {
            newfile.getParentFile().mkdirs();
        }
        Document document = null;
        try {
            document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));

            document.open();
            for (int i = 0; i < fileList.size(); i++) {
                PdfReader reader = new PdfReader(fileList.get(i));
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }

                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
            map.put("mes",e);
        } finally {
            System.gc();
            if (document != null) {
                document.close();
            }
        }
        if(savepath!=""){
            map.put("result","ok");
            map.put("url",savepath);
        }else{
            map.put("result","no");
        }
        return map;
    }

}
